﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using EzDesk.Apps.ServiceImpl.Attendance;
using EzDesk.Apps.ServiceImpl.Message;
using EzDesk.Apps.ServiceImpl.Project;
using EzDesk.Apps.ServiceImpl.Staff;
using System.Threading;
using EzDesk.Utility.Log;

namespace EzDesk.LocalAppServiceHost
{
    public class AppService : ServiceBase
    {
        public AppService()
        {
        }

        private List<ServiceHost> serviceHostPool = new List<ServiceHost>();

        protected override void OnStart(string[] args)
        {
            LogEx.TRACE("LocalAppServiceHost", "AppService Start...");
            startService(typeof (AttendanceService));
            startService(typeof (TopicService));
            startService(typeof (ProjectService));
            startService(typeof (StaffService));
        }

        private void startService(Type type)
        {
            //todo: 开单独的线程解决问题
            work(type);
        }

        protected override void OnStop()
        {
            // todo: 关掉所有服务
            LogEx.TRACE("LocalAppServiceHost", "AppServiceE End");
        }

        void work(Object serviceType)
        {
            Type type = (Type) serviceType;
            ServiceHost serviceHost;

            try
            {
                serviceHost = new ServiceHost(
                    type
                    );
                serviceHost.Open();
                string serviceName = type.Name;

                LogEx.TRACE("LocalAppServiceHost", serviceName + " OK...");
                LogEx.TRACE("LocalAppServiceHost", serviceHost.Description.Endpoints[0].ListenUri.AbsoluteUri);

                serviceHostPool.Add(serviceHost);
            }
            catch (Exception ex)
            {
                LogEx.EXCEPT("LocalAppServiceHost", "AppServiceHost服务挂了", ex);
                // todo: 重启服务
            }
        }
    }
}
